<template>
  <div class="nc-pick">
    <van-field 
      class="nc-pick-field"
      readonly
      :label="label"
      :value="localValue"
      :placeholder="placeholder"
      right-icon="arrow"
      @click="open"
    >
    </van-field>
    <slot name="right"></slot>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        :value-key="valueKey"
        show-toolbar
        :columns="columns"
        @cancel="cancel"
        @confirm="confirm"
      />
    </van-popup>
  </div>
</template>

<script>
import Vue from "vue";
import { Picker, Field, Cell, Popup } from "vant";
import _ from 'underscore';

Vue.use(Picker).use(Field).use(Cell).use(Popup);
export default {
  name: 'nc-pick',
  data() {
    return {
      localValue: '',
      showPicker: false,
      proviceList: []
    };
  },
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    label: String,
    value: [String, Number],
    valueKey: String
  },
  watch: {
    value(val) {
      this.localValue = val;
    }
  },
  methods: {
    confirm(item, index) {
      this.showPicker = false;
      if (_.isObject(item)) {
        this.localValue = item[this.valueKey];
      } else {
        this.localValue = item;
      }
      this.$emit('input', this.localValue);
      this.$emit('confirm', item, index);
    },
    cancel() {
      this.showPicker = false;
    },
    open() {
      this.showPicker = true;
    }
  }
};
</script>

<style lang="less" scoped>
.nc-pick {
  display: flex;
  .nc-pick-field {
    flex: 1;
    width: unset !important;
  }
}
</style>